<template>
  <div>
    <div class="headSearch">
      <div class="searCon">
        <a-form-model
          :label-col="{ span: 6 }" :wrapper-col="{ span: 10 }"
          class="form"
          layout="inline"
          :model="formInline"
          @submit="onSearch"
          @submit.native.prevent
        >
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="goodsName" class="item">
              <a-input v-model="formInline.goods_name" placeholder="goodsName" >
              </a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
             <a-form-model-item label="goodsType" class="item">
              <a-input v-model="formInline.goods_type"  placeholder="goodsType">
              </a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="goodsStatus" class="item">
              <a-input v-model="formInline.goods_status"  placeholder="goodsStatus">
              </a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="goodsDescription" class="item">
               <a-input v-model="formInline.goods_description"  placeholder="goodsStatus">
              </a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="startTime" class="item">
              <!-- <a-input v-model="formInline.goods_status"  placeholder="booking_startTime">
              </a-input> -->
              <a-date-picker
                v-model="formInline.booking_startTime"
                format="YYYY-MM-DD HH:mm:ss"
                :show-time="{ defaultValue: moment1('00:00:00', 'HH:mm:ss') }"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" style="position:relative">
            <a-form-model-item label="endTIme" class="item">
              <!-- <a-input v-model="formInline.goods_status"  placeholder="booking_endTime">
              </a-input> -->
              <a-date-picker
                v-model="formInline.booking_endTime"
                format="YYYY-MM-DD HH:mm:ss"
                :show-time="{ defaultValue: moment1('00:00:00', 'HH:mm:ss') }"
              />
            </a-form-model-item>
            <a-form-model-item class="rightButton">
                <a-button
                  type="primary"
                  html-type="submit"
                >search</a-button>
              </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      </div>
    </div>

    <a-table bordered :data-source="dataSource" :columns="columns" rowKey="goods_id">
      <template slot="operation" slot-scope="text, record">
        <a href="javascript:;" @click="()=>{reserve(record)}">reserve<span v-if="record.me">｜return</span></a>
      </template>
    </a-table>
    <a-modal v-model="showReserve" width="800px" title="reserve Modal" @ok="handleOk">
      <p>
        <span class="title">goodsName:</span>
        {{currentRecord?currentRecord.goods_name:""}}</p>
      <div class="hsitCon">
      <span class="title">reserveHistory:</span>
      <a-table style="margin-bottom:5px" bordered :data-source="modalSource" :columns="columnsModal" rowKey="rowKey">
        <a slot="action" @click="()=>{returnBook(record)}" slot-scope="text, record" href="javascript:;">{{userId==record.userId?"return":""}}</a>
      </a-table>
      </div>
      <span class="title">chooseDate:</span>
      <a-range-picker show-time @change="timeChange">
        <template slot="renderExtraFooter"></template>
      </a-range-picker>
    </a-modal>
  </div>
</template>
<script>
import moment from 'moment';
import api from '../api/index';

export default {
  data() {
    return {
      dataSource: [
      ],
      userId: localStorage.getItem('userId'),
      modalSource: [],
      reserveMoment: null,
      count: 2,
      moment1: moment,
      columnsModal: [
        {
          title: 'userName',
          dataIndex: 'uName',
        },
        {
          title: 'startTime',
          dataIndex: 'startTime',
        },
        {
          title: 'endTime',
          dataIndex: 'endTime',
        },
        {
          title: 'action',
          scopedSlots: { customRender: 'action' },
        },
      ],
      columns: [
        {
          title: 'goodsName',
          dataIndex: 'goods_name',
          width: '30%',
          scopedSlots: { customRender: 'goods_name' },
        },
        {
          title: 'goodsType',
          dataIndex: 'goods_type',
        },
        {
          title: 'goodsStatus',
          dataIndex: 'goods_status',
        },
        {
          title: 'goodsDescription',
          dataIndex: 'goods_description',
        },
        // {
        //   title: 'startTime',
        //   dataIndex: 'startTime',
        // },
        // {
        //   title: 'endTime',
        //   dataIndex: 'endTime',
        // },
        {
          // operation
          width: 160,
          title: 'operation',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      formInline: {
        goods_name: '',
        goods_type: '',
        goods_status: '',
        goods_description: '',
        booking_startTime: '',
        booking_endTime: '',
      },
      currentRecord: null,
      showReserve: false,
    };
  },
  mounted() {
    this.onSearch();
  },
  methods: {
    onCellChange(key, dataIndex, value) {
      const dataSource = [...this.dataSource];
      const target = dataSource.find((item) => item.key === key);
      if (target) {
        target[dataIndex] = value;
        this.dataSource = dataSource;
      }
    },
    reserve(record) {
      this.currentRecord = record;
      this.showReserve = true;
      this.modalSource = record.user_goods.map((item) => ({
        userId: item.f_user_id,
        rowKey: item.relation_id,
        goodId: item.f_goods_id,
        uName: item.user.uname,
        startTime: moment(item.booking_startTime).format('YYYY-MM-DD h:mm:ss'),
        endTime: moment(item.booking_endTime).format('YYYY-MM-DD h:mm:ss'),
      }));
    },
    onSearch() {
      api
        .post('/api/findGoodsByAttrsALL', {
          ...this.formInline,
          booking_endTime: this.formInline.booking_endTime ? this.formInline.booking_endTime : '',
          booking_startTime: this.formInline.booking_startTime ? this.formInline.booking_startTime : '',
        })
        .then((res) => {
          // this.$message.success('search success!');
          const response = res.data.data;
          const userId = localStorage.getItem('userId');
          const newData = response.map((item) => {
            // item
            // let startT = null;
            // let endT = null;
            for (let index = 0; index < item.user_goods.length; index += 1) {
              const element = item.user_goods[index];
              if (userId === `${element.f_user_id}`) {
                item.me = element;
              }
              // const startTime = element.user_goods.booking_startTime;
              // const endTime = element.user_goods.booking_endTime;
              // if (startT) {
              //   startT = startT.getTime() > new Date(startTime).getTime() ? startT : new Date(startTime);
              // } else {
              //   startT = new Date(startTime);
              // }
              // if (endT) {
              //   endT = endT.getTime() > new Date(endT).getTime() ? endT : new Date(endTime);
              // } else {
              //   endT = new Date(endTime);
              // }
            }
            // item.startTime = startT ? moment(startT).format('YYYY-MM-DD h:mm:ss') : '-';
            // item.endTime = endT ? moment(endT).format('YYYY-MM-DD h:mm:ss') : '-';

            return { ...item };
          });
          this.dataSource = newData;
        })
        .catch(({ response }) => {
          this.$message.error(response.data.msg);
        });
    },
    timeChange(e) {
      this.reserveMoment = e;
    },
    returnBook(e) {
      api
        .post('/api/return', {
          // booking_endTime: e.endTime,
          // booking_startTime: e.startTime,
          // f_goods_id: e.goodId,
          // f_user_id: e.userId,
          relation_id: e.rowKey,
        })
        .then(() => {
          this.$message.success('return ok');
          this.showReserve = false;
          this.onSearch();
        })
        .catch(({ response }) => {
          this.$message.error(response.data.msg);
        });
    },
    handleOk() {
      const startTime = this.reserveMoment ? this.reserveMoment[0] : '';
      const endTime = this.reserveMoment ? this.reserveMoment[1] : '';
      const users = this.currentRecord.user_goods;
      let flag = false;
      for (let index = 0; index < users.length; index += 1) {
        if (new Date(startTime).getTime() < new Date(users[index].booking_startTime).getTime() && new Date(users[index].booking_startTime).getTime() < new Date(endTime).getTime()) {
          flag = true;
        }
        if (new Date(startTime).getTime() < new Date(users[index].booking_endTime).getTime() && new Date(users[index].booking_endTime).getTime() < new Date(endTime).getTime()) {
          flag = true;
        }
      }
      if (flag) {
        this.$message.warning('plase check your date');
        return;
      }
      api
        .post('/api/book', {
          f_goods_id: this.currentRecord.goods_id,
          f_user_id: parseInt(localStorage.getItem('userId'), 10),
          booking_startTime: startTime,
          booking_endTime: endTime,
        })
        .then(() => {
          this.$message.success('reserve success');
          this.showReserve = false;
          this.reserveMoment = null;
          this.onSearch();
        })
        .catch(({ response }) => {
          this.$message.error(response.data.msg);
        });
    },
  },
};
</script>
<style scoped>

.form{
  width: 100%;
}
.form .item{
  width: 100%;
}
.editable-cell {
  position: relative;
}
.rightButton{
  position: absolute;
    top: 0;
    right: 10px;
}
.hsitCon{
  display: flex;
}
.title{
  width: 150px;
  padding-right: 10px;
  text-align: right;
  display: inline-block;
}

.editable-cell-input-wrapper,
.editable-cell-text-wrapper {
  padding-right: 24px;
}

.editable-cell-text-wrapper {
  padding: 5px 24px 5px 5px;
}

.editable-cell-icon,
.editable-cell-icon-check {
  position: absolute;
  right: 0;
  width: 20px;
  cursor: pointer;
}

.editable-cell-icon {
  line-height: 18px;
  display: none;
}

.editable-cell-icon-check {
  line-height: 28px;
}

.editable-cell:hover .editable-cell-icon {
  display: inline-block;
}

.editable-cell-icon:hover,
.editable-cell-icon-check:hover {
  color: #108ee9;
}

.editable-add-btn {
}
.headSearch {
  display: flex;
  align-items: center;
  padding-bottom: 8px;
  justify-content: space-between;
}
.headSearch .input {
  width: 50%;
  margin-left: 4px;
}
.searCon {
  flex: 1;
  display: flex;
  align-items: center;
}
</style>
